#include "spageidentify.h"
#include "imageutil.h"

namespace onechchy
{
    SPageIdentify::SPageIdentify(QObject *parent) : QObject(parent)
    {
        mPageNet = cv::dnn::readNetFromTensorflow(this->modelUrl.toStdString().c_str());
        mPageNet.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
        mPageNet.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
    }

    int SPageIdentify::identifyPage(QImage &image)
    {
        cv::Mat mat = QImage2cvMat(image);

        cv::Mat blob = cv::dnn::blobFromImage(mat, 1.0 / 127.5f, cv::Size(64, 64), cv::Scalar(127.5, 127.5, 127.5, 127.5));

        mPageNet.setInput(blob);
        cv::Mat result = mPageNet.forward();

        int curPage = -1;
        if (!result.empty())
        {
            const float* inData = result.ptr<float>(0);

            float maxValue = 0.0f;
            for (int i = 0; i < 8; ++i)
            {
                if (maxValue < inData[i])
                {
                    maxValue = inData[i];
                    curPage = i;
                }
            }
        }

        return curPage + 1;
    }
}
